//
//  LZFCommentController.m
//  LZFBuDieJie
//
//  Created by 梁梓烽 on 16/7/18.
//  Copyright © 2016年 liangzifeng. All rights reserved.
//

#import "LZFCommentController.h"
#import "UIBarButtonItem+LZFBarButtonItem.h"
#import <MJRefresh/MJRefresh.h>
#import <AFNetworking.h>
#import "LZFTopicItem.h"
#import <MJExtension.h>
#import "LZFCommentItem.h"
#import "LZFCommentCell.h"
#import "LZFTopicCell.h"
#import "LZFHeaderVIew.h"



@interface LZFCommentController ()<UITableViewDataSource,UITableViewDelegate>
/** toolView底部的约束 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;
/** tableview子控件 */
@property (weak, nonatomic) IBOutlet UITableView *tableView;
/** http管理者 */
@property(nonatomic,weak)AFHTTPSessionManager  *manager;
/** 最热评论 */
@property(nonatomic,strong)NSArray<LZFCommentItem *> *hotComment;
/** 最新评论数组 */
@property(nonatomic,strong)NSMutableArray<LZFCommentItem *> *latesComment;

@end
@implementation LZFCommentController

#pragma mark -懒加载
-(NSArray<LZFCommentItem *> *)hotComment
{
    if (_hotComment==nil) {
        _hotComment=[NSArray new];
    }
    return _hotComment;
}

-(NSMutableArray<LZFCommentItem *> *)latesComment
{
    if (_latesComment==nil) {
        _latesComment=[NSMutableArray new];
    }
    return _latesComment;
}

-(AFHTTPSessionManager *)manager
{
    if (_manager==nil) {
        _manager=[AFHTTPSessionManager manager];
    }
    return _manager;
}

#pragma mark -viewDidload
-(void)viewDidLoad
{
    
    
    //设置导航条内容
    [self setUpNav];
    
    //设置tableview属性
    [self setUpTableview];
    
    //设置监听
    [self setUpNote];
    
    //设置刷新控件
    [self setUpFresh];
}


#pragma mark -初始化设置

static NSString * const ID=@"commentcell";
static NSString * const headerID=@"headerID";
/**®
 设置导航条内容
 */
-(void)setUpNav
{
    
    //导航条内容
    self.title=@"评论";
    self.navigationItem.rightBarButtonItem=[UIBarButtonItem buttonItemWith:@"comment_nav_item_share_icon" highlightImage:@"comment_nav_item_share_icon_click" target:self selector:@selector(click)];
}


/**®
 设置tableview属性
 */
-(void)setUpTableview
{
    
    //代理数据源
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    
    //注册组头
    [self.tableView registerClass:[LZFHeaderVIew class] forHeaderFooterViewReuseIdentifier:headerID];
    
    //注册cell
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LZFCommentCell class]) bundle:nil] forCellReuseIdentifier:ID];
    
    //背景色
    self.tableView.backgroundColor=LZFGlobalColor;
    
    //取消分割线
    self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    
    
    
    //行高处理
    //设置估算高度,一开始算contentSize用
    self.tableView.estimatedRowHeight=100;
    //告诉tableview所有cell的高度是自动计算(根据约束)
    self.tableView.rowHeight=UITableViewAutomaticDimension;
   
    

    //设置headerView上的cell
    if (self.topicItem.topComment) {
        self.topicItem.topComment=nil;
        self.topicItem.rowHeight=0;
    }
    
    LZFTopicCell *topCell=(LZFTopicCell *)[LZFTopicCell loadXibView];
    topCell.frame=CGRectMake(0, 0, screenW, self.topicItem.rowHeight);
    topCell.topicItem=self.topicItem;
    
    
    UIView *headerView=[[UIView alloc]init];
    headerView.backgroundColor=[UIColor redColor];
    headerView.xmg_height=topCell.xmg_height+2*LZFMargin;
    self.tableView.tableHeaderView=headerView;
    [self.tableView.tableHeaderView addSubview:topCell];
 
}

-(void)click
{
    NSLog(@"click");
}


/** 
 设置监听
 */
-(void)setUpNote
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

-(void)keyboardWillChangeFrame:(NSNotification *)notice
{
    //UIKeyboardFrameEndUserInfoKey
    //UIKeyboardAnimationDurationUserInfoKey
    
    CGFloat duration =[notice.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect endRect=[notice.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    CGFloat contant=screenH-endRect.origin.y;
    self.bottomConstraint.constant=contant;
    
    [UIView animateWithDuration:duration  animations:^{
        [self.view layoutIfNeeded];
    }];
}



/** 
 设置刷新控件
 */

-(void)setUpFresh
{
    self.tableView.mj_header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.mj_footer=[MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}


#pragma mark -网络请求加载数据
/** 
 加载新的数据
 */
-(void)loadNewData
{
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    WeakSelf
    NSMutableDictionary *params=[NSMutableDictionary new];
    params[@"a"] = @"dataList";
    params[@"c"] = @"comment";
    params[@"data_id"] = self.topicItem.ID;
    params[@"hot"] = @1;
    
    
    [self.manager GET:LZFRequestURL parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       // LZFAFNWriteToPlist(@"papa");
        
        if ([responseObject isKindOfClass:[NSArray class]]) {
            
            //结束刷新
            [self.tableView.mj_header endRefreshing];
            //没有评论数据
            return ;
        }
        
        //最热评论
        weakSelf.hotComment=[LZFCommentItem mj_objectArrayWithKeyValuesArray:responseObject[@"hot"]];
        
        //最新评论
        weakSelf.latesComment=[LZFCommentItem mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
    
        
        //刷新tableivew
        [weakSelf.tableView reloadData];
        
        //判断是否加载完了来决定是否隐藏头部刷新控件
        if (weakSelf.latesComment.count>[responseObject[@"total"] intValue]) {
            //头部刷新控件不再显示
            weakSelf.tableView.mj_header.hidden=YES;
        }
        else
        {
            //结束头部刷新
            [weakSelf.tableView.mj_header endRefreshing];

            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //结束头部刷新
        [weakSelf.tableView.mj_header endRefreshing];
        
    }];
}

/**
  加载更多数据
 */

-(void)loadMoreData
{
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    NSMutableDictionary *params=[NSMutableDictionary new];
    params[@"a"] = @"dataList";
    params[@"c"] = @"comment";
    params[@"data_id"] = self.topicItem.ID;
    params[@"lastcid"] =self.latesComment.lastObject.ID;  //上次返回评论的最后一个
    
    
    [self.manager GET:LZFRequestURL parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //加载更多的数据,字典转模型
        NSArray *moreComment=[LZFCommentItem mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        //加入到latesComment数组中
        [self.latesComment addObjectsFromArray:moreComment];
        
        //刷新表格
        [self.tableView reloadData];
        
        //根据数组中的个数个服务器返回的total字段比较,来决定是否隐藏mj_footer控件
        if (self.latesComment.count>[responseObject[@"total"] intValue]) {
            //隐藏底部刷新控件
            // [self.tableView.mj_footer endRefreshingWithNoMoreData]; 提示没有更多的数据
            self.tableView.mj_footer.hidden=YES;
        }
        else {
            //结束底部刷新
            [self.tableView.mj_footer endRefreshing];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
          //结束底部刷新
        [self.tableView.mj_footer endRefreshing];
    }];
}


#pragma mark -scrollviewdelegate

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}


#pragma mark -uitableviewdatasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.hotComment.count) return 2;
    if (self.latesComment.count) return 1;
    return 0;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0&&self.hotComment.count) {
        return self.hotComment.count;
    }
    return self.latesComment.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    LZFCommentCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
    
    NSArray *Comment =self.latesComment;
    if (indexPath.section==0&&self.hotComment.count) {
        Comment=self.hotComment;
   }
    cell.comment=Comment[indexPath.row];
    return cell;
    
}

//tableview的组头显示什么内容
/*
//方法一: 返回的是普通文本的话,可以使用这个方法,直接返回一个字符串
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    

     if (section==0&&self.hotComment.count) {
        return @"最热评论";
    }
    return @"最新评论";
    
}
*/


//如果需要返回自定义组头的话用这个方法
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    //从循环缓冲池中去取
    LZFHeaderVIew *sectionHeaderView=[tableView dequeueReusableHeaderFooterViewWithIdentifier:headerID];
    
    if (section==0&&self.hotComment) {
        
        sectionHeaderView.text=@"最热评论";
        
    }
     sectionHeaderView.text=@"最热评论";
    
    return sectionHeaderView;
}




#pragma mark -uimenucontroller相关
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
    
    UIMenuController *menu=[UIMenuController sharedMenuController];
    //设置Menu的显示项
    menu.menuItems=@[
                     [[UIMenuItem alloc]initWithTitle:@"顶" action:@selector(ding:)],
                     [[UIMenuItem alloc]initWithTitle:@"踩" action:@selector(cai:)],
                     [[UIMenuItem alloc]initWithTitle:@"回复" action:@selector(comment:)],
                     
                     ];
    
    CGRect rect=CGRectMake(0, cell.xmg_height*0.5, screenW, 1);
    [menu setTargetRect:rect inView:cell]; //指向以cell为原点的这个Rect的矩形框
    [menu setMenuVisible:YES animated:YES];//让menu显示
    
}

-(BOOL)canBecomeFirstResponder
{
    return YES;
}


-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    
    if (!self.isFirstResponder) {
        //当控制器不是第一响应者,那么就是文本框是第一响应者,让顶,踩,回复这三个不显示
        if (action==@selector(ding:)||action==@selector(cai:)||action==@selector(comment:)) return NO;
    }
    
    //当控制器是第一响应者,按照父类的默认做法,就显示上面写的顶,踩,回复这三个UIMmeuItem
    return [super canPerformAction:action withSender:sender];
}

-(LZFCommentItem *)selectRowComment
{
    NSInteger section=self.tableView.indexPathForSelectedRow.section;
    NSInteger row= self.tableView.indexPathForSelectedRow.row;
    NSArray *comment=self.latesComment;
    if (section==0&&self.hotComment) {
        comment=self.hotComment;
    }
    return comment[row];
  
}


-(void)ding:(UIMenuController *)menu
{
    
    LZFLog(@"%@",[self selectRowComment].content);
    
}



-(void)cai:(UIMenuController *)menu
{
    LZFLog(@"cai");
}


-(void)comment:(UIMenuController *)menu
{
    LZFLog(@"comment");
    
}




@end
